package com.pzhu.user.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.pzhu.base.common.utils.exceptions.Assert;
import com.pzhu.base.common.utils.result.PageData;
import com.pzhu.user.dao.PermissionDAO;
import com.pzhu.user.domain.entity.Permission;
import com.pzhu.user.domain.entity.converter.PermissionEntityConverter;
import com.pzhu.user.domain.ro.PermissionCreateRO;
import com.pzhu.user.domain.ro.PermissionSearchRO;
import com.pzhu.user.domain.ro.PermissionUpdateRO;
import com.pzhu.user.domain.vo.PermissionSearchVO;
import com.pzhu.user.domain.vo.converter.PermissionVOConverter;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class PermissionService {

    private final PermissionDAO permissionDAO;
    private final PermissionVOConverter permissionVOConverter;
    private final PermissionEntityConverter permissionEntityConverter;

    public PageData<PermissionSearchVO> search(PermissionSearchRO permissionSearchRO) {
        Page<Permission> permissionPage = permissionDAO.search(permissionSearchRO);
        List<PermissionSearchVO> searchVOList = permissionVOConverter.toSearchVOList(permissionPage.getRecords());
        return new PageData<>(searchVOList, permissionPage.getTotalRow());
    }

    public PermissionSearchVO info(Long permissionId) {
        Permission permission = permissionDAO.getByPermissionId(permissionId);
        Assert.assertNotNull(permission, "权限不能为空！");
        return permissionVOConverter.toSearchVo(permission);
    }

    public Long create(PermissionCreateRO ro) {
        boolean existCode = permissionDAO.existCode(ro.getCode());
        Assert.assertFalse(existCode, "权限编码[%s]".formatted(ro.getCode()));
        Permission permission = permissionEntityConverter.of(ro);
        permissionDAO.save(permission);
        return permission.getId();
    }

    public boolean update(Long permissionId, PermissionUpdateRO permissionUpdateRo) {
        Permission permission = permissionDAO.getByPermissionId(permissionId);
        Assert.assertNotNull(permission, "权限不存在！");
        Permission updateEntity = permissionEntityConverter.of(permissionUpdateRo);
        return permissionDAO.updateById(updateEntity);
    }

    public boolean removeById(Long permissionId) {
        return permissionDAO.logicDeleteById(permissionId);
    }

    public boolean removeByIds(List<Long> permissionIdList) {
        return permissionDAO.logicDeleteByIds(permissionIdList);
    }
}
